<?php

/**
 * 通用函数方法
 *
 *
 * @author     Robot
 * @version    1.0
 * @package    Base Framework
 * @access     public
 * @copyright  商业软件,受著作权保护
 * @link       http://***
 */

class Common
{
	/**
	 * 打开debug
	 *
	 * @access public
	 * @param boolean $backtrace 启用回溯
	 * 
	 * @return Void
	 */
	public function debug($backtrace = false)
	{
		define("SQL_DEBUG_ON", true);
		define("MC_DEBUG_ON", true);
		
		//跟踪回溯
		if($backtrace)
		{
			print_r(debug_backtrace());
		}
	}

	/**
	 * 记录日志到指定文件
	 * 
	 * 用于运行时记录数据
	 *
	 * @param array|string $arr 数据
	 * @param boolean $additional 是否追加
	 */
	public function log2file($str, $log_file)
	{
		//创建目录
		$dir = dirname($log_file);
		if(!file_exists($dir))
		{
			mkdir($dir, 0777, true);
		}

		$content = "\r\n[".date("Y-m-d H:i:s")."] ".$str;

		//写入文件
		$logHandle = fopen($log_file, "a+"); //打开日志文件
		if(!is_writable($log_file))
		{
			echo "file：".$log_file." is not writable!";
			exit();
		}
		fwrite ($logHandle, $content."\n");
		fclose($logHandle); //关闭日志指针
	}

	/**
	 * 编码
	 * 
	 * 说明：用于数组序列化入库
	 *
	 * @access public
	 * @param Array $arr 需要处理的数组
	 * 
	 * @return String
	 */
	function encode($arr)
	{
		return mysql_escape_string(serialize($arr));
	}

	/**
	 * 解码
	 * 
	 * 说明：处理从库中得到的序列化数据
	 *
	 * @access public
	 * @param String $str 需要处理的字符串
	 * 
	 * @return String
	 */
	function decode($str)
	{
		return unserialize($str);
	}

	/**
	 * 301跳转
	 *
	 * @access public
	 * @param String $url 跳转到url
	 * 
	 * @return Void
	 */
	public function header301($url)
	{
		if(ini_get('zlib.output_compression'))
		{
			ini_set('zlib.output_compression', 'Off');
		}

		header("HTTP/1.1 301 Moved Permanently");
		header("Location: " . $url);
		exit();
	}

	/**
	 * 404页面
	 *
	 * @access public
	 * @param String $url 跳转到url
	 * 
	 * @return Void
	 */
	public function header404($note=0)
	{
		if(ini_get('zlib.output_compression'))
		{
			ini_set('zlib.output_compression', 'Off');
		}

		header("HTTP/1.1 404 Not Found");
		header("Status: 404 Not Found");

		if($note)
		{
			echo '<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
  <title>404 - Not Found</title>
 </head>
 <body>
  <h1>404 - Not Found</h1>
 </body>
</html>
';
		exit;
		}
	}

	/**
	 * url跳转
	 *
	 * @access public
	 * @param String $url 跳转到url
	 * 
	 * @return Void
	 */
	public function header($url)
	{
		if(ini_get('zlib.output_compression'))
		{
			ini_set('zlib.output_compression', 'Off');
		}

		header("Location: " . $url);
		exit();
	}

	/**
	 * 加载插件文件
	 *
	 * @access public
	 * @param string $filename 插件文件名
	 * 
	 * @return Void
	 */
	public static function load($filename)
	{
		$filename = LIBRARY_DIR . 'Plugins/' . $filename . '.class.php';
		
		if(!file_exists($filename))
		{
			throw new MyException("file $filename not exists!");
		}
		
		include_once $filename;
	}

	/**
	 * 加载子系统函数文件
	 *
	 * @access public
	 * @param string $filename 函数文件名
	 * 
	 * @return Void
	 */
	public static function loadFunc($filename)
	{
		$filename = LIBRARY_DIR . 'Func/' . ucfirst($filename).'.class.php';

		if(!file_exists($filename))
		{
			throw new MyException("file $filename not exists!");
		}
		
		include_once $filename;
	}

	/**
	 * 打包成xml数据
	 * 
	 * 说明：用在ajax数据返回
	 *
	 * @access public
	 * @param String $content 字符串
	 * 
	 * @return Void
	 */
	public function packXml($content)
	{
		header("Content-type: text/xml; charset=utf-8");
		echo '<?xml version="1.0" encoding="utf-8"?><root><![CDATA['.$content.']]></root>';
		exit;
	}

	/**
	 * 获取ip简要信息
	 *
	 * @access public
	 * @param none
	 * 
	 * @return String
	 */
	public function getIpSimple($ips="")
	{
		if($ips)
		{
			$ips = explode(",", $ips);
		}
		else
		{
			$ips[] = $_SERVER['HTTP_X_FORWARDED_FOR'];
			$ips[] = $_SERVER['REMOTE_ADDR'];
		}

		if($ips)
		foreach($ips as $ip)
		{
			$ip = trim($ip);
			if($ip)
			{
				$t = explode(".", $ip);
				if($t[0] == '172' && ($t[1] < 16 || $t[1] > 31))
				{
					break;
				}
				if(!in_array($t[0], array("192", "10")))
				{
					break;
				}
			}
		}

		return $ip;
	}

	/**
	 * 获取ip归属地
	 *
	 * @access public
	 * @param none
	 * 
	 * @return String
	 */
	public function getIpLocation($ip)
	{
		require_once LIBRARY_DIR."Plugins/Ip2location.class.php";

		$ip = self::getIpSimple($ip);

		$o = new Ip2Location();
		if($ip)
		{
			$o->qqwry($ip);
			$l = str_replace('CZ88.NET', '', $o->Country.$o->Local);
			$location = iconv("gb2312", "UTF-8", $o->Country);
		}
		else
		{
			$location = '未知';
		}
		return $location;
	}

	/**
	 * 生成随机字符串
	 *
	 * @access public
	 * @param int $length
	 * 
	 * @return String
	 */
	public function getRandom($iStrLen = 8)
	{
		$aChar = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
		
		$iCharLen = count($aChar) - 1;
		$sRandVal = "";
		for($i = 0; $i < $iStrLen; $i++)
		{
			srand((double)microtime() * 1000000);
			$sRandVal .= $aChar[rand(0, $iCharLen)];
		}
		Return $sRandVal;
	}

	/**
	 * 生成随机数字
	 *
	 * @access public
	 * @param int $length
	 * 
	 * @return String
	 */
	public function getNumberRandom($iStrLen = 6)
	{
		$randStr = str_shuffle("0123456789");
		return substr($randStr, 0, $iStrLen);
	}

	/**
	 * 全角转半角
	 *
	 * @access public
	 * @param string $str 要转换的字符串
	 * 
	 * @return String
	 */
	public function sbcToDbc($str)
	{
		$string = Array('１'=>'1', '２'=>'2', '３'=>'3', '４'=>'4', '５'=>'5', '６'=>'6', '７'=>'7', '８'=>'8', '９'=>'9', '０'=>'0', 'ａ'=>'a', 'ｂ'=>'b', 'ｃ'=>'c', 'ｄ'=>'d', 'ｅ'=>'e', 'ｆ'=>'f', 'ｇ'=>'g', 'ｈ'=>'h', 'ｉ'=>'i', 'ｊ'=>'j', 'ｋ'=>'k', 'ｌ'=>'l', 'ｍ'=>'m', 'ｎ'=>'n', 'ｏ'=>'o', 'ｐ'=>'p', 'ｑ'=>'q', 'ｒ'=>'r', 'ｓ'=>'s', 'ｔ'=>'t', 'ｕ'=>'u', 'ｖ'=>'v', 'ｗ'=>'w', 'ｘ'=>'x', 'ｙ'=>'y', 'ｚ'=>'z', 'Ａ'=>'A', 'Ｂ'=>'B', 'Ｃ'=>'C', 'Ｄ'=>'D', 'Ｅ'=>'E', 'Ｆ'=>'F', 'Ｇ'=>'G', 'Ｈ'=>'H', 'Ｉ'=>'I', 'Ｊ'=>'J', 'Ｋ'=>'K', 'Ｌ'=>'L', 'Ｍ'=>'M', 'Ｎ'=>'N', 'Ｏ'=>'O', 'Ｐ'=>'P', 'Ｑ'=>'Q', 'Ｒ'=>'R', 'Ｓ'=>'S', 'Ｔ'=>'T', 'Ｕ'=>'U', 'Ｖ'=>'V', 'Ｗ'=>'W', 'Ｘ'=>'X', 'Ｙ'=>'Y', 'Ｚ'=>'Z', '　'=>' ', ','=>',', '。'=>'.', '？'=>'?', '＜'=>'<', '＞'=>'>', '〔'=>'[', '〕'=>']', '＊'=>'*', '＆'=>'&', '＾'=>'^', '％'=>'%', '＃'=>'#', '＠'=>'@', '！'=>'!', '('=>'(', ')'=>')', '＋'=>'+', '－'=>'-', '｜'=>'|', '：'=>':', ';'=>';', '｛'=>'{', '｝'=>'}', '／'=>'/', '”'=>'"');
		return strtolower(strtr($str, $string));
	}

	/**
	 * 获取字符串中的中文
	 *
	 * @access public
	 * @param string $str 字符串
	 * 
	 * @return String
	 */
	public function getCn($str)
	{
		return preg_replace("/[^一-龥]/u", "", $str);
	}

	/**
	 * 中文字符串截取
	 *
	 * @access public
	 * @param string $str	原串
	 * @param int $length	截取长度
	 * @param string $etc	更多标识
	 * 
	 * @return String
	 */
	public function strCut($str, $length = 10, $etc = '…')
	{
		if(!$str)
		{
			return '';
		}
		$substr = mb_substr($str, 0, $length, "utf-8");
		if(mb_strlen($str, "utf-8") > mb_strlen($substr, "utf-8"))
		{
			return $substr . $etc;
		}
		return $substr;
	}

	/**
	 * 获取当前microtime
	 *
	 * @access public
	 * @param none
	 * 
	 * @return int
	 */
	public function getMicrotime()
	{
		list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec + (float)$sec);
	}

	/**
	 *
	 * 设置Cookie
	 *
	 * @access public
	 * @param String $key
	 * @param String $val
	 * 
	 * @return String
	 */
	public function setcookie($key, $value)
	{
		setcookie($key, $value, time()+86400, "/", ".".DOMAIN_ROOT);
	}

	/**
	 * curl请求
	 *
	 * @param
	 */
	function curlRequest($remote_server, $post_string=null, $second=60)
	{
		$ch = curl_init();
		if(strlen($remote_server) > 5 && strtolower(substr($remote_server,0,5)) == "https" )
		{
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		}
		curl_setopt($ch,CURLOPT_URL,$remote_server);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post_string);
		curl_setopt($ch,CURLOPT_TIMEOUT,$second); 
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2');
		curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: text/xml', 'Content-length: '.strlen($post_string)));

		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}

	/**
	 * 跳转
	 *
	 * @access public
	 * @param  String $url 跳转地址
	 * @param  String $url 打开方式
	 * 
	 * @return void
	 */
	public function forward($url, $target='window'){
		echo "<script>".$target.".location.href='".$url."';</script>";
		exit();
	}

	/**
	 * 获取参数名
	 *
	 * @access public
	 * @param  String $id 值
	 * 
	 * @return String
	 */
	public function getArgsName($arr){
		if($arr == 0)
		{
			return "无";
		}
		if(is_array($arr))
		{
			foreach($arr as $id)
			{
				if($id == 0)
				{
					$R[] = "无";
				}
				else
				{
					$R[] = VarData::$CFArgsname[$id];
				}
			}
			return $R;
		}
		else
		{
			return VarData::$CFArgsname[$arr];
		}
	}

	/**
	 * 组装参数
	 *
	 * @access public
	 * @param  String $url 跳转地址
	 * @param  String $url 打开方式
	 * 
	 * @return void
	 */
	public function assign($arr)
	{
		if($arr){
			foreach($arr as $key => $val)
			{
				switch ($key) {
					case 'work_huanjing':
						$arr[$key] ="";
						foreach ($val as $v) {
							$arr[$key].= VarData::$firstData[$key][$v]."|";
						}
						$arr[$key]=trim($arr[$key],"|");
						break;
					default:
						if(array_key_exists($key,VarData::$firstData)){
							$arr[$key] = VarData::$firstData[$key][$val];
						}else{
							$arr[$key] = "";
						}
						break;
					}
			}
		}
		return $arr;
	}

	public function assOther($arr,$type){
		if($arr){
			switch ($type) {
				case 1:
					foreach($arr as $key => $val)
					{
						switch ($key) {
							default:
								if(array_key_exists($key,VarData::$one)){
									$arr[$key] = VarData::$one[$key][$val];
								}else{
									$arr[$key] = $val?$val:"";
								}
								break;
							}
					}
					break;
				case 2:
					foreach($arr as $key => $val)
					{
						switch ($key) {
							case 'shijiqingkuang':
								$arr[$key] ="<ul>";
								foreach ($val as $v) {
									$arr[$key].= "<li>".VarData::$two[$key][$v]."</li>";
								}
								$arr[$key] .="</ul>";
								break;
							
							default:
								if(array_key_exists($key,VarData::$two)){
									$arr[$key] = VarData::$two[$key][$val];
								}else{
									$arr[$key] =  $val?$val:"";
								}
								break;
							}
					}
					break;
				case 3:
					foreach($arr as $key => $val)
					{
						switch ($key) {
							case 'cixing':
								$arr[$key] ="";
								foreach ($val as $v) {
									$arr[$key].= VarData::$three[$key][$v]."|";
								}
								$arr[$key]=trim($arr[$key],"|");
								break;
							default:
								if(array_key_exists($key,VarData::$three)){
									$arr[$key] = VarData::$three[$key][$val];
								}else{
									$arr[$key] =  $val?$val:"";
								}
								break;
							}
					}
					break;
				case 4:
					foreach($arr as $key => $val)
					{
						switch ($key) {
							case 'shijiqingkuang':
								$arr[$key] ="<ul>";
								foreach ($val as $v) {
									$arr[$key].= "<li>".VarData::$four[$key][$v]."</li>";
								}
								$arr[$key] .="</ul>";
								break;
							
							default:
								if(array_key_exists($key,VarData::$four)){
									$arr[$key] = VarData::$four[$key][$val];
								}else{
									$arr[$key] =  $val?$val:"";
								}
								break;
							}
					}
					break;
				case 5:
					foreach($arr as $key => $val)
					{
						switch ($key) {
							default:
								if(array_key_exists($key,VarData::$five)){
									$arr[$key] = VarData::$five[$key][$val];
								}else{
									$arr[$key] =  $val?$val:"";
								}
								break;
							}
					}
					break;
				case 6:
					foreach($arr as $key => $val)
					{
						switch ($key) {
							case 'shijiqingkuang':
								$arr[$key] ="<ul>";
								foreach ($val as $v) {
									$arr[$key].= "<li>".VarData::$six[$key][$v]."</li>";
								}
								$arr[$key] .="</ul>";
								break;
							
							default:
								if(array_key_exists($key,VarData::$six)){
									$arr[$key] = VarData::$six[$key][$val];
								}else{
									$arr[$key] =  $val?$val:"";
								}
								break;
							}
					}
					break;
				default:
					# code...
					break;
			}
		}
		return $arr;
	}
}
?>
